package com.wang.transfer.util.springBean.resolver;

import com.wang.transfer.util.springBean.annotation.Mapper;
import com.wang.transfer.util.springBean.beanConfig.BeanFactory;

import java.util.ArrayList;
import java.util.logging.Logger;

/**
 * MapperAnnotationResolver: @Mapper注解解析器
 * @author Mr.wang
 */
public class MapperAnnotationResolver {

    private final Logger logger = Logger.getLogger(MapperAnnotationResolver.class.getName());

    private final BeanFactory beanFactory;

    public MapperAnnotationResolver(BeanFactory beanFactory, ArrayList<Class> allClass) {

        this.beanFactory = beanFactory;

        for (Class aClass : allClass) {
            if (aClass.isAnnotationPresent(Mapper.class)) {
                logger.info("Mapper class: " + aClass);
                try {
                    Object clazz = aClass.newInstance();
                    String beanName = aClass.getName().substring(aClass.getName().lastIndexOf(".") + 1);
                    beanName = beanName.substring(0, 1).toLowerCase() + beanName.substring(1);
                    logger.info("Mapper beanName: " + beanName);
                    // 缓存bean
                    beanFactory.beanRegister.registerSingletonBean(beanName, clazz);
                } catch (InstantiationException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
